
package andre.grids.filesystem.client;

import andre.grids.filesystem.common.DirectoryOperations;
import andre.grids.network.PeerObjects;
import andre.grids.util.PathUtils;
import java.rmi.RemoteException;

/**
 *
 * @author andre
 */
public class RDirectory {
    
    private String dirName;
    private RemoteServer remoteServer;
    
    public RDirectory(String dirName, RemoteServer server) {
        this.dirName = dirName;
        remoteServer = server;
    }
    
    public boolean exists() throws RemoteException {        
        return remoteServer.getDirOp().exists(dirName);
    }
    
    public RDirectory create() throws RemoteException {
        
        String parent = getParent();
        RDirectory dir = new RDirectory(parent, remoteServer);
        
        if (!dir.exists() && !getDirName().equals("/")) // verifica se o diretório pai não existe
            //se o diretório pai não existe ele deve ser criado
            dir.create();
        
        remoteServer.getDirOp().createDirectory(dirName);
        return this;
    }
    
    public void delete() throws RemoteException {
        remoteServer.getDirOp().deleteDirectory(dirName);
    }
    
    public RDirectory getChild(String childName) {
        RDirectory dir = new RDirectory(dirName + "/" + childName,remoteServer);
        return dir;
    }
    
    public String[] list() throws RemoteException {
        return remoteServer.getDirOp().listContents(dirName);
    }
    
    public String getMasterFor(String dirName) throws RemoteException {
        return remoteServer.getDirOp().getDirectoryMaster(dirName);
    }
    
    public String getDirName() {
        return dirName;
    }
    
    public String getParent() {
        return PathUtils.extractParentPath(dirName);
    }
}
